package cn.heyige.backend.aspect;

import cn.heyige.backend.annotation.RequireVip;
import cn.heyige.backend.service.MembershipService;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Aspect
@Component
@Slf4j
@RequiredArgsConstructor
public class VipPermissionAspect {
    
    private final MembershipService membershipService;
    
    @Around("@annotation(requireVip)")
    public Object checkVipPermission(ProceedingJoinPoint joinPoint, RequireVip requireVip) throws Throwable {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (attributes == null) {
            throw new RuntimeException("无法获取请求上下文");
        }
        
        HttpServletRequest request = attributes.getRequest();
        String userId = (String) request.getAttribute("userId");
        
        if (userId == null ) {
            throw new RuntimeException("未提供有效的认证令牌");
        }

        if (!membershipService.isVipMember(userId)) {
            throw new RuntimeException(requireVip.message());
        }
        
        return joinPoint.proceed();
    }
}